﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using BCL;
using System.IO;
using UploadingControl.SilverlightService;
using System.Collections.ObjectModel;

namespace UploadingControl
{
    public partial class NewsDetailPage : UserControl
    {
        PageMode _Mode;
        LogoInformation _logoInformation;

        public NewsDetailPage(PageMode pageMode, LogoInformation logoinformation, List<Theme> themes)
        {
            InitializeComponent();
            _logoInformation = logoinformation;

            this.Loaded += (s, e) =>
            {
                // registering events here
                // because there was problem in xaml
                YearComboBox.SelectionChanged += new SelectionChangedEventHandler(YearComboBox_SelectionChanged);
                MonthComboBox.SelectionChanged += new SelectionChangedEventHandler(MonthComboBox_SelectionChanged);
                MagNoComboBox.SelectionChanged += new SelectionChangedEventHandler(MagNoComboBox_SelectionChanged);

                ThemeComboBox.ItemsSource = themes;
                ThemeComboBox.SelectedIndex = 0;

                CheckDate();
                SetValue("");
                GetMenu();
                _Mode = pageMode;
                if (pageMode == PageMode.Edit)
                {
                    YearComboBox.IsEnabled = false;
                    MonthComboBox.IsEnabled = false;
                    MagNoComboBox.IsEnabled = false;
                    datePicker2.IsEnabled = false;
                    datePicker1.IsEnabled = false;
                    //datePicker1.IsEnabled = false;
                    datePicker1.SelectedDate = logoinformation.FromDate;
                    fileFarman.CompleteUploadedURL = logoinformation.FarmanImage;
                    fileHeader.CompleteUploadedURL = logoinformation.HeaderImage;
                    fileLog.CompleteUploadedURL = logoinformation.LogoImage;
                    fileFarman.Finalize();
                    fileHeader.Finalize();
                    fileLog.Finalize();
                    //datePicker2.IsEnabled = false;
                    datePicker2.SelectedDate = logoinformation.CurrentDate;

                    char[] ch = { '/' };
                    string[] splitUrl = logoinformation.Url.Split(ch, StringSplitOptions.RemoveEmptyEntries);

                    string[] years = new string[] { "Select Year", "2012", "2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020" };
                    string[] months = new string[] { "Select Month", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12" };
                    string[] magazineNos = new string[] { "", "mag-01", "mag-02" };

                    SetDropdownIndex(YearComboBox, splitUrl[0]);
                    SetDropdownIndex(MonthComboBox, splitUrl[1]);
                    SetDropdownIndex(MagNoComboBox, splitUrl[2]);

                    var selectedItem = themes.Where(x => x.Id == logoinformation.ThemeId).FirstOrDefault();
                    if (selectedItem != null)
                    {
                        ThemeComboBox.SelectedItem = selectedItem;
                    }
                }

            };
        }

        public void SetDropdownIndex(ComboBox cmb, string str)
        {
            int intCounter = 0;
            foreach (ComboBoxItem currentItem in cmb.Items)
            {

                if (currentItem.Tag.ToString() == str)
                {
                    //intCounter++;
                    cmb.SelectedIndex = intCounter++;
                    break;
                }
                else
                    intCounter++;
            }
        }

        public List<LookUp> lstLookUp { get; set; }
        public void GetMenu()
        {
            SilverlightServiceClient client = new SilverlightServiceClient();
            client.GetMenuCompleted += (se, arg) =>
                {
                    lstLookUp = arg.Result;
                    lstMenu.DataContext = this;
                };

            client.GetMenuAsync();
        }

        private void hyperlinkButton1_Click(object sender, RoutedEventArgs e)
        {
            if (datePicker1.SelectedDate != null)
            {
                HyperlinkButton hyper = sender as HyperlinkButton;
                if (_logoInformation == null)
                {
                    _logoInformation = new LogoInformation();
                    _logoInformation.Detail = new List<LogoDetail>();
                }

                var menu = lstLookUp.Where(f => f != null).Where(f => f.LookUpID == Convert.ToInt32(hyper.Tag)).FirstOrDefault();
                var isMenuExist = _logoInformation.Detail.Where(f => f.MenuId == menu.LookUpID).FirstOrDefault();
                if (isMenuExist == null)
                {
                    isMenuExist = new LogoDetail();
                    isMenuExist.MenuId = menu.LookUpID;
                    isMenuExist.MenuName = menu.Description;
                }
                NewDetailPopup popup = new NewDetailPopup(_Mode, isMenuExist, datePicker1.SelectedDate.Value.ToShortDateString().Replace("/", "-"));

                popup.Closing += (s, d) =>
                    {
                        if (popup.DialogResult != null && popup.DialogResult.Value)
                        {
                            if (_Mode == PageMode.Edit)
                            {
                                // remvoe the existing detail info from list
                                _logoInformation.Detail.Remove(_logoInformation.Detail.Where(x => x.MenuId == popup.LogoDetail.MenuId).FirstOrDefault());
                            }


                            _logoInformation.Detail.Add(popup.LogoDetail);

                        }
                    };
                popup.Show();
            }
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }

        private void datePicker1_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            CheckDate();

        }

        private void CheckDate()
        {
            String url = string.Empty;
            DateTime? fromDate = null;
            DateTime? toDate = null; // assuming current date as to date


            #region get year month and day and create url of logoInformation
            var yearBox = (ComboBoxItem)YearComboBox.SelectedItem;
            var monthBox = (ComboBoxItem)MonthComboBox.SelectedItem;
            var magNoBox = (ComboBoxItem)MagNoComboBox.SelectedItem;

            if (datePicker2.SelectedDate != null && datePicker1.SelectedDate != null)
            {
                //var year = Convert.ToString(yearBox.Tag);
                //var month = Convert.ToString(monthBox.Tag);
                //var magNo = Convert.ToString(magNoBox.Tag);

                //if (year != "0" && month != "0" && magNo != "0")
                {
                    url = String.Format("/{0}/{1}/{2}/", datePicker1.SelectedDate.Value.Year, ZeroPad(datePicker1.SelectedDate.Value.Month), ZeroPad(datePicker1.SelectedDate.Value.Day) + "-" + ZeroPad(datePicker2.SelectedDate.Value.Day));

                    //if (magNo == "mag-01")
                    //{
                    //    fromDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
                    //    toDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 15);
                    //}
                    //else
                    //{
                    //    fromDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 16);

                    //    // get last day of current month
                    //    DateTime firstDayOfTheMonth = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), 1);
                    //    var lastDay = firstDayOfTheMonth.AddMonths(1).AddDays(-1);
                    //    toDate = new DateTime(Convert.ToInt32(year), Convert.ToInt32(month), lastDay.Day);
                    //}
                }
            }
            #endregion


            if (String.IsNullOrEmpty(url) == false)
            {
                fileFarman.isUploadFile = true;
                fileHeader.isUploadFile = true;
                fileLog.isUploadFile = true;


                if (_logoInformation == null)
                {
                    _logoInformation = new LogoInformation();
                    _logoInformation.Detail = new List<LogoDetail>();
                }

                _logoInformation.Url = url;

                //datePicker1.SelectedDate =  //fromDate;
                //datePicker2.SelectedDate = toDate;

                SetValue(datePicker1.SelectedDate.Value.ToShortDateString().Replace("/", "-"));
            }
            else
            {
                fileFarman.isUploadFile = false;
                fileHeader.isUploadFile = false;
                fileLog.isUploadFile = false;

            }
        }

        private void SetValue(string date)
        {
            fileFarman.Initialize("/documents/Farman", "Farman" + date, "Cover Page Thumbnail");
            fileHeader.Initialize("/documents/Header", "Idaria" + date, "Idaria");
            fileLog.Initialize("/documents/Logo", "Logo" + date, "Cover Page");
        }
        public String ZeroPad(Int32 number)
        {
            return (number <= 9 ? "0" : "") + number;
        }
        private void button4_Click(object sender, RoutedEventArgs e)
        {
            SilverlightServiceClient client = new SilverlightServiceClient();
            _logoInformation.FarmanImage = fileFarman.CompleteUploadedURL;
            _logoInformation.LogoImage = fileLog.CompleteUploadedURL;
            _logoInformation.HeaderImage = fileHeader.CompleteUploadedURL;

            // save theme in logo information
            _logoInformation.ThemeId = ((Theme)ThemeComboBox.SelectedItem).Id;

            client.SaveCompleted += (se, arg) =>
                {
                    if (arg.Error == null)
                    {
                        OpenListPage();
                    }

                };

            _logoInformation.CreatedBy = App.UserId;
            _logoInformation.UpdatedBy = App.UserId;

            if (String.IsNullOrEmpty(_logoInformation.Url) == false)
            {
                client.AlreadyDateCompleted += (se, arg) =>
                    {
                        if (arg.Result)
                        {
                            _logoInformation.FromDate = datePicker1.SelectedDate.Value;
                            _logoInformation.CurrentDate = datePicker2.SelectedDate.Value;
                            client.SaveAsync(_logoInformation);
                        }
                        else
                        {
                            MessageBox.Show("Selected date already exist", "Error", MessageBoxButton.OK);
                        }
                    };

                if (_Mode == PageMode.Add)
                {
                    var url = _logoInformation.Url;
                    if (datePicker1.SelectedDate.Value < datePicker2.SelectedDate.Value)
                        client.AlreadyDateAsync(datePicker1.SelectedDate.Value);
                    else
                    {
                        MessageBox.Show("To Date should be greated than From date");
                    }
                }
                else if (_Mode == PageMode.Edit)
                {
                    _logoInformation.FromDate = datePicker1.SelectedDate.Value;
                    _logoInformation.CurrentDate = datePicker2.SelectedDate.Value;

                    client.SaveAsync(_logoInformation);
                }


            }
            else
            {
                MessageBox.Show("Please select date");
            }
        }

        private void button5_Click(object sender, RoutedEventArgs e)
        {
            OpenListPage();
        }
        void OpenListPage()
        {
            StackPanel panel = ((StackPanel)this.Parent);
            if (panel != null)
            {
                panel.Children.Clear();
                panel.Children.Add(new NewListPage());
            }
        }



        private void YearComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CheckDate();
        }

        private void MonthComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CheckDate();
        }

        private void MagNoComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            CheckDate();
        }

    }
}
